<?php
/**
 * Created by PhpStorm.
 * Script Name: Botfriend.php
 * Create: 2021/12/21 12:00
 * Description:
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace plugin\wechat\app\tenant\controller;

use app\common\constant\Common;
use plugin\wechat\app\model\BotMember;
use plugin\wechat\app\service\Bot as BotService;
use plugin\wechat\app\service\BotFriend as FriendService;
use plugin\wechat\app\TenantController;
use Support\Request;

class Botfriend extends TenantController
{
    /**
     * @var BotMember
     */
    protected $model;

    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
        $this->model = new BotMember();
        set_time_limit(0);
    }

    /**
     * 好友列表
     * @param Request $request
     * @return mixed|\support\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function index(Request $request)
    {
        $bot = $request->botInfo;
        if (request()->isPost()) {
            $post_data = input('post.');
            $where = [
                $this->tenantWhere(),
                ['type','=', BotService::FRIEND],
                ['uin','=', $bot['uin']]
            ];
            !empty($post_data['search_key']) && $where[] = ['nickname|remark_name|username|wxid', 'like', '%' . $post_data['search_key'] . '%'];
            $query = $this->model->where($where);
            $total = $query->count();
            if ($total) {
                $list = $query->page($post_data['page'], $post_data['limit'])
                    ->select();
            }else{
                $list = [];
            }
            return $this->success('success', '', ['total' => $total, 'list' => $list]);
        }

        $tip = "<ul><li>注意：</li><li>当前的备注名称就是您对该好友的微信备注</li></ul>";
        $builder = new ListBuilder();
        $builder->setSearch([
            ['type' => 'text', 'name' => 'search_key', 'title' => '关键词', 'placeholder' => 'wxid、微信号、昵称、备注名称']
        ])
            ->setTip($tip)
            ->addTopButton('self', ['text'=>'拉取最新好友', 'href' => url('syncFriends'), 'data-ajax' => 1])
            ->addTableColumn(['title' => 'Wxid', 'field' => 'wxid', 'minWidth' => 90])
            ->addTableColumn(['title' => '头像', 'field' => 'headimgurl', 'type' => 'picture', 'minWidth' => 100])
            ->addTableColumn(['title' => '昵称', 'field' => 'nickname', 'minWidth' => 90])
            ->addTableColumn(['title' => '微信号', 'field' => 'username', 'minWidth' => 90])
            ->addTableColumn(['title' => '备注名称', 'field' => 'remark_name', 'minWidth' => 70])
            ->addTableColumn(['title' => '性别', 'field' => 'sex', 'minWidth' => 70, 'type' => 'enum', 'options' => Common::sex()])
            ->addTableColumn(['title' => '省份', 'field' => 'province', 'minWidth' => 90])
            ->addTableColumn(['title' => '城市', 'field' => 'city', 'minWidth' => 90])
            ->addTableColumn(['title' => '操作', 'minWidth' => 200, 'type' => 'toolbar'])
            ->addRightButton('edit', ['title' => '设置备注名'])
            ->addRightButton('delete', ['title' => '删除好友', 'href' => url('deleteFriendPost', ['id' => '__data_id__'])]);

        return $builder->show();
    }

    /**
     * 删除好友
     * @return \support\Response
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function deleteFriendPost(){
        $bot = \request()->botInfo;
        $id = input('post.ids');
        if(! $friend = $this->model->where([
            $this->tenantWhere(),
            ['uin', '=', $bot['uin']]
        ])
            ->find($id)){
            return  $this->error('数据不存在');
        }
        $res = BotService::getRobotClient($bot)->deleteFriend([
            'robot_wxid' => $bot['uin'],
            'to_wxid' => $friend['wxid']
        ]);
        if($res['code']){
            $this->model->where('id', $id)->delete();
            return $this->success('操作成功!');
        }else{
            return $this->error($res['errmsg']);
        }
    }

    /**
     * 设置备注
     * @return mixed|\support\Response
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function edit()
    {
        $bot = \request()->botInfo;
        $id = input('id', null);
        $data = $this->model->where([
            $this->tenantWhere()
        ])
            ->find($id);
        if (!$data) {
            return $this->error('参数错误!');
        }
        if(request()->isPost()){
            $post_data = input('post.');
            $res = BotService::getRobotClient($bot)->setFriendRemarkName([
                'robot_wxid' => $bot['uin'],
                'to_wxid' => $data['wxid'],
                'note' => $post_data['remark_name']
            ]);
            if($res['code']){
                $this->model->update(['id' => $id, 'remark_name' => $post_data['remark_name']]);
                return $this->success('设置成功', '');
            }
            return $this->error($res['errmsg']);
        }

        // 使用FormBuilder快速建立表单页面
        $builder = new FormBuilder();
        $builder->setMetaTitle('设置备注名')
            ->setPostUrl(url('edit'))
            ->addFormItem('id', 'hidden', 'ID', 'ID')
            ->addFormItem('remark_name', 'text', '备注名称', '30字内', [], 'required maxlength=30')
            ->setFormData($data);

        return $builder->show();
    }

    /**
     * 同步好友数据
     * @return \support\Response
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function syncFriends(){
        $bot = \request()->botInfo;
        $total = FriendService::pullFriends($bot);
        return $this->success('此次同步到' . $total . '位好友');
    }
}